package com.efounder.http.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.util.Log;

import com.efounder.email.adapter.DetailListAdapter.DownHandler;
import com.efounder.email.model.AttachFile;
import com.pansoft.resmanager.ResFileManager;
import com.utilcode.util.UriUtils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

/**
 * 邮件点击附件 下载并打开附件 通过post请求 为了下载普光邮箱的附件 20216.04.20
 *现在改成get请求 2016.08.09
 * @author yqs
 * 
 */
@SuppressLint("DefaultLocale")
public class DownEmailAttachPostUtil {

	private String directory;
	private Context mcontext;
	private String urlStr;
	private String fileName;
	private AttachFile attachFile;
	private DownHandler downHandler;
	Thread thread;

	public DownEmailAttachPostUtil(Context mcontext, String urlStr,
								   AttachFile attachFile, DownHandler downHandler) {
		super();
		this.downHandler = downHandler;
		this.attachFile = attachFile;
		this.mcontext = mcontext;
		this.urlStr = urlStr;
		this.fileName = attachFile.getAttachName();
		directory = ResFileManager.MEETING;
		File file = new File(directory);
		if (!file.exists() && !file.isDirectory()) {
			System.out.println("//不存在");
			file.mkdir();
		} else {
			System.out.println("//目录存在");
		}

	}

	/**
	 * 执行下载
	 */
	public void taskStart() {
		MyThread myThread = new MyThread(urlStr);
		thread = new Thread(myThread);
		thread.start();

	}

	public void taskEnd() {
		if (thread != null && thread.isAlive()) {
			thread.interrupt();

		}

	}

	public class MyThread extends Thread {
		String url = "https://pgyd.zyof.com.cn/ESPWTN/servlet/DownLoad?cookie=&url=";
		String urlString;

		public MyThread(String urlStr) {

			this.urlString = urlStr;
		};

		@Override
		public void run() {
			super.run();
			fileName = URLDecoder.decode(fileName);
			Log.i("tag", "fileName=" + fileName);

			File file = new File(directory, fileName);
			if (file.exists()) {
				Log.i("tag", "The file has already exists.");
				openFile(fileName);
				return;
			}
			downHandler.sendEmptyMessage(0);
			try {
		
				StringBuffer stringBuffer = new StringBuffer();
				stringBuffer = stringBuffer.append(urlString)
						.append("?mailid=").append(attachFile.getId())
						.append("&filename=")
						.append(URLEncoder.encode(file.getName(), "GBK"));
				String httpString = URLEncoder.encode(stringBuffer.toString(),
						"GBK");

				System.out.println("普光邮箱下载后缀--------" + httpString);
				HttpClient client = new DefaultHttpClient();
				//client.getParams().setIntParameter("http.socket.timeout",8000);//设置超时
				HttpGet get = new HttpGet(url + httpString);
				HttpResponse response = client.execute(get);

				if (HttpStatus.SC_OK == response.getStatusLine()
						.getStatusCode()) {
					HttpEntity entity = response.getEntity();
					InputStream input = entity.getContent();

					writeToSDCard(fileName, input);
					input.close();
					openFile(fileName);
				} else {
					openFile(null);
				}

			} catch (Exception e) {
				openFile(null);
			}
		}

	}

	public void openFile(String fileName) {
		downHandler.sendEmptyMessage(1);
		if (fileName == null) {
			downHandler.sendEmptyMessage(2);

			return;
		}
		downHandler.sendEmptyMessage(3);

		File file = new File(directory, fileName);
		Log.i("tag", "Path=" + file.getAbsolutePath());

		try {
			Intent intent = getFileIntent(file);
			if (isIntentAvailable(mcontext, intent)) {
				mcontext.startActivity(intent);
			} else {
				downHandler.sendEmptyMessage(4);

			}
		} catch (Exception e) {
			downHandler.sendEmptyMessage(5);

		}
	}

	public Intent getFileIntent(File file) {

		Uri uri = UriUtils.getUriForFile(file);
		String type = getMIMEType(file);
		Log.i("tag", "type=" + type);
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(uri, type);
		return intent;
	}

	public void writeToSDCard(String fileName, InputStream input) {

		// if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
		// File directory=Environment.getExternalStorageDirectory();
		File file = new File(directory, fileName);
		// if(file.exists()){
		// Log.i("tag", "The file has already exists.");
		// return;
		// }
		try {
			FileOutputStream fos = new FileOutputStream(file);
			byte[] b = new byte[2048];
			int j = 0;
			while ((j = input.read(b)) != -1) {
				fos.write(b, 0, j);
			}
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/*
		 * }else{ Log.i("tag", "NO SDCard."); }
		 */
	}

	private String getMIMEType(File f) {
		String type = "";
		String fName = f.getName();
		/* 取得扩展名 */
		String end = fName
				.substring(fName.lastIndexOf(".") + 1, fName.length())
				.toLowerCase();

		/* 依扩展名的类型决定MimeType */
		if (end.equals("pdf")) {
			type = "application/pdf";//
		} else if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
				|| end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
			type = "audio/*";
		} else if (end.equals("3gp") || end.equals("mp4")) {
			type = "video/*";
		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg") || end.equals("bmp")) {
			type = "image/*";
		} else if (end.equals("apk")) {
			/* android.permission.INSTALL_PACKAGES */
			type = "application/vnd.android.package-archive";
		} else if (end.equals("pptx") || end.equals("ppt")) {
			type = "application/vnd.ms-powerpoint";
		} else if (end.equals("docx") || end.equals("doc")) {
			type = "application/msword";
		} else if (end.equals("xlsx") || end.equals("xls")) {
			type = "application/vnd.ms-excel";
		} else {
			// /*如果无法直接打开，就跳出软件列表给用户选择 */
			type = "*/*";
		}
		return type;
	}

	/**
	 * 判断Intent 是否存在 防止崩溃
	 * 
	 * @param context
	 * @param intent
	 * @return
	 */
	private boolean isIntentAvailable(Context context, Intent intent) {
		final PackageManager packageManager = context.getPackageManager();
		List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
				PackageManager.GET_ACTIVITIES);
		return list.size() > 0;
	}
}
